<?php

namespace ApiWF\Controller;

use Common\Controller\ApibaseController;
use Think\Exception;

class ActivityController extends ApibaseController
{

    public function index()
    {

        $act_model = D('ActivityView');
        $order =  ['update_time'=>'desc','ActivityRelationships.listorder'=>'desc'];
        $act_model = $act_model->order($order);

        //照置顶推荐-进行中-未开始-已结束排序

        //置顶
        $whereTop = [
            'ActivityCategory.name' => ['LIKE', '%活动%'],
            'Activity.act_status'=>2,//  `act_status` smallint(1) DEFAULT '0' COMMENT '活动状态，2-置顶,3-推荐到首页,1-正常，-1-删除，0-待审核',
        ];
        //进行中
        $whereOn =  [
            'ActivityCategory.name' => ['LIKE', '%活动%'],
            'Activity.act_status'=>1,//  `act_status` smallint(1) DEFAULT '0' COMMENT '活动状态，2-置顶,3-推荐到首页,1-正常，-1-删除，0-待审核',
            '_string'=>'UNIX_TIMESTAMP() > UNIX_TIMESTAMP(Activity.start_time) AND UNIX_TIMESTAMP() < UNIX_TIMESTAMP(Activity.end_time)',
        ];

        //未开始
        $whereWill =  [
            'ActivityCategory.name' => ['LIKE', '%活动%'],
            'Activity.act_status'=>1,//  `act_status` smallint(1) DEFAULT '0' COMMENT '活动状态，2-置顶,3-推荐到首页,1-正常，-1-删除，0-待审核',
            '_string'=>'UNIX_TIMESTAMP() < UNIX_TIMESTAMP(Activity.start_time)',
        ];
        //过期
        $whereExpire =  [
            'ActivityCategory.name' => ['LIKE', '%活动%'],
            'Activity.act_status'=>1,//  `act_status` smallint(1) DEFAULT '0' COMMENT '活动状态，2-置顶,3-推荐到首页,1-正常，-1-删除，0-待审核',
            '_string'=>'UNIX_TIMESTAMP() > UNIX_TIMESTAMP(Activity.end_time)',
        ];
        $tops = $act_model->where($whereTop)->order(['Activity.update_time'=>'desc'])->select();
        $ons = $act_model->where($whereOn)->order(['Activity.start_time'=>'desc'])->select();
        $wills = $act_model->where($whereWill)->order(['Activity.start_time'=>'asc'])->select();
        $expires = $act_model->where($whereExpire)->order(['Activity.end_time'=>'desc'])->select();


        //为分页
        $total_page = 1;
        $current_page = 1;
        $page_size = 1000;
        $list = array_merge($tops,$ons,$wills,$expires);
        $data = compact('total_page', 'current_page', 'page_size', 'list');

        $activity = $data['list'];
        foreach ($activity as $key => $vo) {
            $activity[$key]['act_pic'] = qiniu_mirror_image_url_act($vo);
            $start_time = strtotime($vo['start_time']);
            $end_time = strtotime($vo['end_time']);
            // 2:进行中 3:未开始 4:过期
            if(time() >$end_time){
                $activity[$key]['label_status'] = '4';//过期
            }else if(time() < $start_time){
                $activity[$key]['label_status'] = '3';//未开始
            }else {
                $activity[$key]['label_status'] = '2';//进行中
            }
        }


        if ($activity) {
            $data['list'] = $activity;
            $this->jsonReturn($data, '获取信息成功！');
        } else {
            $this->error("获取信息失败！");
        }
    }
    //废弃
    public function getDetail()
    {
        $act_model = M("Activity");
        $id = I("id", 0, 'intval');
        $where['id'] = $id;
        $where['act_status'] = array('neq', '-1');
        $activity = $act_model->where($where)->order(array("update_time" => "desc"))->field("id,act_title,act_description,act_content,act_pic,start_time,end_time,update_time,reward_coin")->find();
        if ($activity) {
            //过滤html
            htmlStringToPlainStirngArray($activity,'act_content');


            $activity['act_pic'] = qiniu_mirror_image_url_act($activity);
            $uid = $this->parseTokenUID();

            $where = ['uid' => $uid, 'act_id' => $id];

            //判断用户是否收藏活动
            $is_favorated = D('UserActivityFavorites')->where($where)->find();
            $activity['is_add_favarate'] = empty($is_favorated) ? 0 : 1;

            //判断用户是否参加活动
            $is_participate = M('UsersActivity')->where($where)->find();
            $activity['is_participate'] = empty($is_participate) ? 0 : 1;

            $end_time = strtotime($activity['end_time']);

            $activity['is_expire'] = $end_time > time() ? 0 : 1;

            $this->jsonReturn2($activity);
        }
        else {
            $this->error('活动已经删除或者已经取消');
        }
    }

    public function getFavor()
    {
        $favor_model = M("UserActivityFavorites");
        $uid = $this->parseTokenUID();

        $act_id = I("act_id", 0, 'intval');
        if (!$act_id) {
            $this->error('act_id:int必须参数,');
        }

        $type = I("type", 0, 'intval');
        if (!$type) {
            $this->error('type:int必须参数,');
        }

        if ($type == 1) {
            //添加收藏记录
            $data = array(
                'uid' => $uid,
                'act_id' => $act_id,
                'create_time' => date('Y-m-d H:i:s'),
            );
            $is_exist = $favor_model->where(['uid' => $uid, 'act_id' => $act_id])->find();
            if (!empty($is_exist)) {
                $this->success('已经收藏');
            }
            $result = $favor_model->add($data);
            if ($result) {
                $this->success('收藏成功！');
            } else {
                $this->error("收藏失败！");
            }
        }

        if ($type == 2) {
            //删除收藏
            $result = $favor_model->where(array('act_id' => $act_id, 'uid' => $uid))->delete();
            if ($result) {
                $this->success('取消成功！');
            } else {
                $this->error("取消失败！");
            }
        }

    }

    /**
     * 参加活动
     */
    public function getActivity()
    {


        $uact_model = M("UsersActivity");
        $uid = $this->parseTokenUID();

        $act_id = I("act_id", 0, 'intval');
        $type = I("type", 0, 'intval');


        //奖励金币
        $act_info = D('Activity')->where(['id' => $act_id])->find();
        $reward_coin = intval($act_info['reward_coin']);

        if ($type == 1) {
            //参加活动
            $data = array(
                'uid' => $uid,
                'act_id' => $act_id,
                'create_time' => date("Y-m-d H:i:s"),
            );
            $where = ['act_id' => $act_id, 'uid' => $uid];
            $is_exist = $uact_model->where($where)->find();
            if (!empty($is_exist)) {
                $this->error('活动已参加');
            }

            try{
                $uact_model->add($data);
                //写入金币记录表
                $title = '参加活动';
                $discription = '获取金币' . $reward_coin;
                //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换 7:参加活动
                //$this->addCoinRecord($uid, 7, $title, $discription, $reward_coin);

                $title = $act_info['act_title'];
                $image = qiniu_mirror_image_url_act($act_info);
                $start_time = $act_info['start_time'];
                $end_time = $act_info['end_time'];
                $end_time_one_day_ago = date('Y-m-d H:i:s', strtotime($end_time.' - 1 day'));

                $start_time_int = strtotime($start_time);
                if(time() > $start_time_int){
                    //活动开始了
                    $sendTime = date('Y-m-d H:i:s');
                }else {
                    $sendTime = $start_time;
                }
                $body = $act_info['act_title'];
                //发送消息
                //开始提醒
                $act_begin_message = [
                    'uid'=>$uid,
                    'message_type_id'=>5,
                    'title'=>$title,
                    'content'=>"【关注活动开始提醒】{$body}",
                    'image'=>$image,
                    'act_start_time'=>$start_time,
                    'act_end_time'=>$end_time,
                    'obj_id'=>$act_id,
                    'obj_type'=>'activity',
                    'display_type'=>2,//2:活动-开始提醒
                    'send_time'=>$sendTime,
                    'create_time'=>date('Y-m-d H:i:s'),
                ];
                //结束提醒
                $act_end_message = [
                    'uid'=>$uid,
                    'message_type_id'=>5,
                    'title'=> $title,
                    'content'=>"【关注活动明日结束提醒】{$body}",
                    'image'=>$image,
                    'act_start_time'=>$start_time,
                    'act_end_time'=>$end_time,
                    'obj_id'=>$act_id,
                    'obj_type'=>'activity',
                    'display_type'=>3,//3:活动-结束提醒
                    'send_time'=>$end_time_one_day_ago,
                    'create_time'=>date('Y-m-d H:i:s'),
                ];

                //产生过期提醒消息
                $user_message_model = M('UserMessages');
                $user_message_model->add($act_end_message);
                $user_message_model->add($act_begin_message);

                $this->success('参加活动成功！');

            }catch (Exception $e){
                $this->error($e->getMessage());
            }



        } else {
            //退出活动
            try{
                $uact_model->where(array('act_id' => $act_id, 'uid' => $uid))->delete();
                //写入金币记录表
                $title = '取消活动';
                $discription = '扣减金币' . $reward_coin;
                //1:金币抽奖 2:金币奖品 3:积分兑换 4:新手任务 5:每日签到 6:金币兑换 7:参加活动 8:退吹活动
                //$this->addCoinRecord($uid, 8, $title, $discription, -$reward_coin);

                //删除消息
                M('UserMessages')->where(['uid'=>$uid,'obj_type'=>'activity','obj_id'=>$act_id])->delete();

                $this->success('取消成功！');

            }catch (Exception $e){
                $this->error($e->getMessage());
            }
        }

    }


    public function shareDetail(){
        $id = I('id',0,'intval');
        $act_model = M("Activity");
        $where['id'] = $id;
        $where['act_status'] = array('neq', '-1');
        $activity = $act_model->where($where)->field("id,act_title,act_description,act_pic,reward_coin")->find();
        if ($activity) {
            $activity['act_pic'] = qiniu_mirror_image_url_act($activity);
            $host = C('host',null,'https://api.loogsin.com');
            $uri = U('/H5/Web/act',['id'=>$id]);
            $activity['share_url'] = $host.$uri ;
            $this->jsonReturn2($activity);
        }
        else {
            $this->error('活动已经删除或者已经取消');
        }
    }
}

